package io.renren.modules.bs.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.ExcelUtil;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.bs.dao.BsExtractRecordDao;
import io.renren.modules.bs.entity.*;
import io.renren.modules.bs.service.*;
import io.renren.modules.bs.vo.ExportExtraRecordExcelVo;
import io.renren.modules.bs.vo.IndexVo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Service("bsExtractRecordService")
public class BsExtractRecordServiceImpl extends ServiceImpl<BsExtractRecordDao, BsExtractRecordEntity> implements BsExtractRecordService {

    @Autowired
    private BsExtractRecordDetailService extractRecordDetailService;

    @Autowired
    private BsExtractDetailPatientService extractDetailPatientService;

    @Autowired
    private BsHospitalService hospitalService;

    @Autowired
    private BsDepartmentPatientImgService imgService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<BsExtractRecordEntity> page = this.page(
                new Query<BsExtractRecordEntity>().getPage(params),
                new QueryWrapper<BsExtractRecordEntity>().orderByDesc("extract_record_id")
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void removeRecords(List<Long> asList) {

        QueryWrapper<BsExtractRecordDetailEntity> detailEntityQueryWrapper = new QueryWrapper<>();
        detailEntityQueryWrapper.in("record_id",asList);
        List<BsExtractRecordDetailEntity> detailEntityList = this.extractRecordDetailService.list(detailEntityQueryWrapper);
        Set<Long> collect = detailEntityList.stream().map(BsExtractRecordDetailEntity::getExtractRecordDetail).collect(Collectors.toSet());
        QueryWrapper<BsExtractDetailPatientEntity> bsExtractDetailPatientEntityQueryWrapper = new QueryWrapper<>();
        bsExtractDetailPatientEntityQueryWrapper.in("detail_id",collect);
        List<BsExtractDetailPatientEntity> list = extractDetailPatientService.list(bsExtractDetailPatientEntityQueryWrapper);
        Set<Long> detailPatientIdSet = list.stream().map(BsExtractDetailPatientEntity::getExtractDetailPatientId).collect(Collectors.toSet());
        //
        boolean b = this.removeByIds(asList);
        if(!b){
            throw new RuntimeException("移除记录失败");
        }
        boolean remove = this.extractRecordDetailService.remove(detailEntityQueryWrapper);
        if(!remove){
            throw new RuntimeException("移除详情失败");
        }
        boolean remove1 = this.extractDetailPatientService.remove(bsExtractDetailPatientEntityQueryWrapper);
        if(!remove1){
            throw new RuntimeException("移除详情设计的患者失败");
        }
        //更新图片 detailPatientIdSet
        UpdateWrapper<BsDepartmentPatientImgEntity> bsDepartmentPatientImgEntityUpdateWrapper = new UpdateWrapper<>();
        bsDepartmentPatientImgEntityUpdateWrapper.in("extract_detail_patient_id",detailPatientIdSet);
        bsDepartmentPatientImgEntityUpdateWrapper.set("extract_detail_patient_id",null);
        boolean update = this.imgService.update(bsDepartmentPatientImgEntityUpdateWrapper);
    }

    @Override
    public List<IndexVo> getData(Map<String, Object> params) {

        List<IndexVo> indexVoList = this.baseMapper.getExtraNum();
        List<BsHospitalEntity> list = this.hospitalService.list();
        Map<Long, IndexVo> indexVoMap = indexVoList.stream().collect(Collectors.toMap(IndexVo::getHospitalId, a -> a, (k1, k2) -> k1));
        for (BsHospitalEntity bsHospitalEntity:list) {
            if(!indexVoMap.containsKey(bsHospitalEntity.getHospitalId())){
                IndexVo indexVo = new IndexVo();
                indexVo.setHospitalId(bsHospitalEntity.getHospitalId());
                indexVo.setHospitalName(bsHospitalEntity.getHospitalName());
                indexVo.setExtraNum(0);
                indexVoList.add(indexVo);
                indexVoMap.put(indexVo.getHospitalId(),indexVo);
            }
        }
        int count = this.count();
        IndexVo indexVo = new IndexVo();
//        indexVo.setHospitalId();
        indexVo.setHospitalName("总抽取次数");
        indexVo.setExtraNum(count);
        indexVoList.add(indexVo);
        return indexVoList;
    }

    @Override
    public void exportFile(Long extractRecordId, HttpServletResponse response) {

        //获取所有的主推
        List<ExportExtraRecordExcelVo> exportList = this.baseMapper.getExportList(extractRecordId);
        for (ExportExtraRecordExcelVo exportExtraRecordExcelVo:exportList) {
            if(exportExtraRecordExcelVo.getIsDone() == 1){
                exportExtraRecordExcelVo.setIsDoneValue("是");
            }else {
                exportExtraRecordExcelVo.setIsDoneValue("否");
            }
        }
        Map<Long, List<ExportExtraRecordExcelVo>> map = exportList.stream().collect(Collectors.groupingBy(ExportExtraRecordExcelVo::getExtractRecordDetail));
        exportList = new ArrayList<>();
        for (Map.Entry<Long,List<ExportExtraRecordExcelVo>> entry:map.entrySet()) {
            ExportExtraRecordExcelVo exportExtraRecordExcelVo = entry.getValue().get(0);
            ExportExtraRecordExcelVo mainExportExtraRecordExcelVo = new ExportExtraRecordExcelVo();
            BeanUtil.copyProperties(exportExtraRecordExcelVo,mainExportExtraRecordExcelVo);
            mainExportExtraRecordExcelVo.setSubExtraRecordExcelVos(entry.getValue());
            exportList.add(mainExportExtraRecordExcelVo);
        }

//        exportList.
        String[] title={"医院","科室","数量","是否完成","姓名","性别","身份证号"};
        //excel名称
        String fileName = "抽取记录.xls";
        //sheet名
        String sheetName = "抽取记录";

        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, exportList,null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();os.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}